# -*- coding: utf-8 -*-
"""
Agent Boss 简单功能测试
"""

import os
import sys
import django
from django.conf import settings

# 添加项目路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 配置Django设置
if not settings.configured:
    settings.configure(
        DEBUG=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            }
        },
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'rest_framework',
            'agent_boss',
        ],
        ROOT_URLCONF='agent_boss.urls',
        SECRET_KEY='test-secret-key',
        USE_TZ=True,
    )

django.setup()

from django.test import TestCase, Client
from django.contrib.auth.models import User
import json
from unittest.mock import patch, MagicMock


def test_text_cleaning():
    """测试文本清理功能"""
    print("🧪 测试文本清理功能...")
    
    try:
        from agent_boss.views import clean_text
        
        # 测试基本功能
        result1 = clean_text("Hello World")
        print(f"✅ 基本文本: '{result1}'")
        
        # 测试中文
        result2 = clean_text("你好世界")
        print(f"✅ 中文文本: '{result2}'")
        
        # 测试空文本
        result3 = clean_text("")
        print(f"✅ 空文本: '{result3}'")
        
        print("✅ 文本清理功能测试通过")
        return True
        
    except Exception as e:
        print(f"❌ 文本清理功能测试失败: {e}")
        return False


def test_agent_import():
    """测试Agent导入"""
    print("🧪 测试Agent导入...")
    
    try:
        from agent_boss.agents.boss_agent import BossAgent
        print("✅ BossAgent导入成功")
        
        # 测试工具导入
        from agent_boss.agents.tools.resume_tool import build_resume_tools
        from agent_boss.agents.tools.job_tool import build_job_tools
        from agent_boss.agents.tools.knowledge_tool import build_knowledge_tools
        
        print("✅ 工具模块导入成功")
        return True
        
    except Exception as e:
        print(f"❌ Agent导入失败: {e}")
        return False


def test_api_view():
    """测试API视图"""
    print("🧪 测试API视图...")
    
    try:
        from agent_boss.views import BossAgentAPIView
        print("✅ BossAgentAPIView导入成功")
        
        # 测试视图类
        view = BossAgentAPIView()
        print("✅ BossAgentAPIView实例化成功")
        
        return True
        
    except Exception as e:
        print(f"❌ API视图测试失败: {e}")
        return False


def test_urls():
    """测试URL配置"""
    print("🧪 测试URL配置...")
    
    try:
        from agent_boss.urls import urlpatterns
        print(f"✅ URL配置加载成功，共{len(urlpatterns)}个路由")
        
        for pattern in urlpatterns:
            print(f"  - {pattern.pattern}")
        
        return True
        
    except Exception as e:
        print(f"❌ URL配置测试失败: {e}")
        return False


def test_mock_api_call():
    """测试模拟API调用"""
    print("🧪 测试模拟API调用...")
    
    try:
        from django.test import Client
        from django.contrib.auth.models import User
        
        # 创建测试客户端
        client = Client()
        
        # 创建测试用户
        user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )
        
        # 准备请求数据
        data = {
            'question': '测试问题',
            'session_id': 'test_session'
        }
        
        # 发送请求（不提供认证，应该返回认证失败）
        response = client.post(
            '/agent_boss/chat/',
            data=json.dumps(data),
            content_type='application/json'
        )
        
        # 验证响应
        if response.status_code == 200:
            response_data = response.json()
            if response_data.get('code') == 0 and '认证失败' in response_data.get('message', ''):
                print("✅ API调用测试通过（认证失败符合预期）")
                return True
            else:
                print(f"❌ 意外的响应: {response_data}")
                return False
        else:
            print(f"❌ HTTP状态码错误: {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ 模拟API调用测试失败: {e}")
        return False


def run_all_tests():
    """运行所有测试"""
    print("🚀 开始运行Agent Boss功能测试...")
    print("=" * 60)
    
    tests = [
        ("文本清理功能", test_text_cleaning),
        ("Agent导入", test_agent_import),
        ("API视图", test_api_view),
        ("URL配置", test_urls),
        ("模拟API调用", test_mock_api_call),
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        print(f"\n📋 {test_name}:")
        try:
            if test_func():
                passed += 1
                print(f"✅ {test_name} - 通过")
            else:
                print(f"❌ {test_name} - 失败")
        except Exception as e:
            print(f"❌ {test_name} - 异常: {e}")
    
    print("\n" + "=" * 60)
    print(f"📊 测试结果: {passed}/{total} 通过")
    
    if passed == total:
        print("🎉 所有测试通过！Agent Boss功能正常")
        print("\n🎯 可以开始使用Agent Boss API了！")
        return True
    else:
        print("❌ 部分测试失败，请检查代码")
        return False


if __name__ == '__main__':
    run_all_tests()
